package com.bluewap.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class Configuration {
	private static Configuration config = null;
	private static Map<String, Properties> map1;
	private static Map<String, Long> map2;
	
	private String rootPath;
	private Configuration(){
		map1 = new HashMap<String, Properties>();
		map2 = new HashMap<String, Long>();
	}

	public Properties loadFile(String fileName) throws FileNotFoundException, IOException{
		File fin;
		if(rootPath != null)
			fin = new File(rootPath + "/WEB-INF/" + fileName);
		else
			fin = new File(fileName);

		Properties prop = null;
		// new config
		if(map1.get(fileName) == null){
			prop = new Properties();
			FileInputStream fis = new FileInputStream(fin);
			prop.load(fis);
			map1.put(fileName, prop);
			map2.put(fileName, System.currentTimeMillis());
			fis.close();
		}
		// old config
		else{
			// check last read with last updated
			long lastRead = map2.get(fileName);
			long lastUpdated = fin.lastModified();
			prop = map1.get(fileName);
			if(lastRead < lastUpdated){
				prop.load(new FileInputStream(fin));
				map1.put(fileName, prop);
				map2.put(fileName, System.currentTimeMillis());
			}
		}
		return prop;
	}

	public static Configuration getInstance() {
		if(config == null)
			config = new Configuration();
		return config;
	}

	public void setRootPath(String rootPath) {
		this.rootPath = rootPath;
	}

	public String getRootPath() {
		return rootPath;
	}
}